MSB(Most Significant Bit)
最上位ビットのこと
xbit数が決まっていれば次のようにして計算できる
code:msb.go
package main
import (
"fmt"
)
func main() {
assert(0b0, 0b0)
assert(0b1, 0b1)
assert(0b10, 0b10)
assert(0b11, 0b10)
assert(0b00101000, 0b00100000)
assert(
0b1000000000101010101,
0b1000000000000000000,
)
}
// MSB Calculates Most Significant Bit of x
func MSB(x uint32) uint32 {
x = x | x>>1
x = x | x>>2
x = x | x>>4
x = x | x>>8
x = x | x>>16
x += 1
x = x >> 1
return x
}
func assert(in, expect uint32) {
got := MSB(in)
result := func() string {
switch {
case got == expect:
return "OK"
default:
return "FAILED"
}
}()
fmt.Printf("%q: expect %b, got %b for input: %b\n", result, expect, got, in)
}